/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, DatePicker, Input, Select, message, Spin } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
@connect(({ empinfo, loading }) => ({
  loading: loading.models.empinfo,
  dataInfo: empinfo.dataInfo,
}))
@Form.create()
class BasicForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      empId: null,
      dictList: ['ADD_ID_TYPE', 'GENDER', 'NATIONALITY'], // 字典
      NATIONALITY: [],
      ADD_ID_TYPE: [],
      GENDER: [],
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    const { dictList } = this.state;
    const id = queryString.parse(location.search).empId;
    this.setState({ empId: id });
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: dictList,
    }).then(data => {
      dictList.map(dict => {
        this.setState({ [dict]: data[dict] });
      });
      this.getInfo(id);
    });
  }

  // 获取数据信息
  getInfo = empId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'empinfo/getEmpDetail',
      payload: {
        empId,
      },
    });
  };

  // 提交
  submitAll = () => {
    const { empId } = this.state;
    const { dispatch, form } = this.props;
    let submitData = {};
    form.validateFieldsAndScroll((error, values) => {
      if (!error) {
        values.birthDate = values.birthDate.format('YYYY-MM-DD');
        submitData = { ...values, empId };
        // console.log(submitData);
        dispatch({
          type: 'empinfo/updateSubmit',
          payload: submitData,
        }).then(response => {
          if (response.success) {
            message.success(`${response.message || '修改成功！'}`, 2, () => {
              router.push('/maindatamanage/emplinfo/index');
            });
          } else {
            message.warning(`${response.message || '修改数据失败：服务器端错误！'}`);
          }
        });
      }
    });
  };

  // 渲染函数
  render() {
    const {
      loading,
      form: { getFieldDecorator },
      dataInfo,
    } = this.props;
    const { ADD_ID_TYPE, GENDER, NATIONALITY } = this.state;
    // 证件类型
    const cardType = ADD_ID_TYPE.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    // 性别
    const gender = GENDER.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    // 政治面貌
    const polStatus = NATIONALITY.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>员工信息修改</span>}
              className={styles.card}
            >
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="姓名">
                    {getFieldDecorator('empName', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: dataInfo.empName,
                    })(<Input placeholder="请输入" maxLength={30} />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="证件类型">
                    {getFieldDecorator('cardType', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: dataInfo.cardType,
                    })(<HOCSelect placeholder="请选择">{cardType}</HOCSelect>)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="证件号">
                    {getFieldDecorator('cardNo', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: dataInfo.cardNo,
                    })(<Input placeholder="请输入" maxLength={18} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="性别">
                    {getFieldDecorator('gender', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: dataInfo.gender,
                    })(<HOCSelect placeholder="请选择">{gender}</HOCSelect>)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="出生日期">
                    {getFieldDecorator('birthDate', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: moment(dataInfo.birthDate),
                    })(
                      <DatePicker
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                        placeholder="请选择"
                      />
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="国籍">
                    {getFieldDecorator('cntry', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: dataInfo.cntry,
                    })(
                      <HOCSelect placeholder="请选择" showSearch optionFilterProp="children">
                        {polStatus}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            <FooterToolbar style={{ width: '100%' }}>
              <Button onClick={() => window.history.back()} style={{ marginRight: 10 }}>
                取消
              </Button>
              <Button type="primary" onClick={this.submitAll}>
                提交
              </Button>
            </FooterToolbar>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default BasicForm;
